<!--
 * @Author: 黄达全
 * @Date: 2024-07-29 17:13:01
 * @LastEditTime: 2024-07-29 17:13:07
-->
<script lang="ts" setup>
import type { UserForm, UserVO } from "@/common/type/user"
import UserApi from "@/api/model/user"
import LevelApi from "@/api/model/level"
import drawer from "@/components/drawer.vue"
import { useTable } from "@/hooks/useTable"
import useElementPlus from "@/hooks/useElementPlus"
import { ref } from "vue"
import selectImage from "@/components/selectImage.vue"

const { message } = useElementPlus()

const {
    height,
    getData,
    pageSize,
    total,
    tableData,
    drawerRef,
    initForm,
    del,
    handleSelectionChange,
    editId,
    isAddMode,
    submitHandle,
    tableRef,
    tableHeight,
    formRules,
    getDataByPage
} = useTable<UserVO, UserForm>({
    fetchData: (page, pageSize) => UserApi.page(page, pageSize),
    addItem: (form) => UserApi.add(form),
    deleteItem: (ids) => UserApi.delete(ids),
    updateItem: (form) => UserApi.update(form),
    initForm: {
        username: "",
        password: "",
        nickname: "",
        avatar: "",
        userLevelId: null,
        phone: "",
        email: "",
        status: 0
    },
    formRules: {
        username: [
            { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [
            { required: true, message: "请输入密码", trigger: "blur" }
        ],
        nickname: [
            { required: true, message: "请输入昵称", trigger: "blur" }
        ],
        avatar: [
            { required: true, message: "请上传头像", trigger: "blur" }
        ],
        userLevelId: [
            { required: true, message: "请选择会员等级", trigger: "change" }
        ],
        phone: [
            { required: true, message: "请输入手机号码", trigger: "blur" }
        ],
        email: [
            { required: true, message: "请输入邮箱", trigger: "blur" }
        ],
        status: [
            { required: true, message: "请选择状态", trigger: "change" }
        ]
    },
    title: "用户"
})

const uploadImage=ref(null)
// 打开新增抽屉
const openAddDrawer = async() => {
    if(uploadImage.value){
        //@ts-ignore
        uploadImage.value.init_checked()!
    }
    try {
        const { data } = await LevelApi.page(1, 10)
        levelOptions.value = data.records.map(item => ({
            value: item.id,
            label: item.name
        }))
    } catch (error) {
        message({
            message: "获取会员等级数据失败",
            type: "error"
        })
    } finally {
        levelLoading.value = false
    }

    isAddMode.value = true
    initForm.username = ''
    initForm.password = ''
    initForm.nickname = ''
    initForm.avatar = ''
    initForm.userLevelId = levelOptions.value[0].value
    initForm.phone = ''
    initForm.email = ''
    initForm.status = 0
    drawerRef.value.open()
}

// 打开编辑抽屉
const openEditUserDrawer = async(user: UserVO) => {

    try {
        const { data } = await LevelApi.page(1, 10)
        levelOptions.value = data.records.map(item => ({
            value: item.id,
            label: item.name
        }))
    } catch (error) {
        message({
            message: "获取会员等级数据失败",
            type: "error"
        })
    } finally {
        levelLoading.value = false
    }
    isAddMode.value = false
    initForm.username = user.username || ''
    initForm.password = user.password || ''
    initForm.nickname = user.nickname || ''
    initForm.avatar = user.avatar || ''
    initForm.userLevelId = user.userLevelId || 1
    initForm.phone = user.phone || ''
    initForm.email = user.email || ''
    initForm.status = user.status
    editId.value = user.id
    drawerRef.value.open()
}

const changeStatusHandle = async (e: number, row: UserVO) => {
    const { code } = await UserApi.update({
        id: row.id,
        username: row.username!,
        password: row.password,
        nickname: row.nickname,
        avatar: row.avatar,
        userLevelId: row.userLevelId,
        phone: row.phone,
        email: row.email,
        status: e
    })
    if (code == 1) {
        message({
            message: "修改状态成功",
            type: "success"
        })
        getData()
    } else {
        message({
            message: "修改状态失败",
            type: "error"
        })
    }
}
// 会员等级数据
const levelOptions = ref<{ label: string, value: number }[]>([])
const levelLoading = ref(false)

// 获取会员等级数据
const getLevelData = async (e:any) => {
    const { scrollTop, scrollHeight, clientHeight } = e.target
    if (!levelLoading.value && scrollTop + clientHeight >= scrollHeight - 5) {
        levelLoading.value = true
    try {
        const { data } = await LevelApi.page(1, 10)
        levelOptions.value = data.records.map(item => ({
            value: item.id,
            label: item.name
        }))
    } catch (error) {
        message({
            message: "获取会员等级数据失败",
            type: "error"
        })
    } finally {
        levelLoading.value = false
    }
    }
}

const handleImageSelect = (imageList: any) => {
    if (imageList && imageList.length > 0) {
        initForm.avatar = imageList[0].url
    }
}
</script>

<template>
    <div class="userPage">
        <el-card class="card" :body-style="{ height: height + 'px', padding: '10px 10px 0 10px' }">
            <template #header>
                <div class="card-header">
                    <el-button color="var(--primary-theme-color)" icon="el-icon-plus" size="small" type="primary"
                        @click="openAddDrawer">新增用户</el-button>
                    <el-button size="small" type="danger" @click="del" icon="el-icon-delete">批量删除</el-button>
                </div>
            </template>
            <div class="card-body">
                <div class="user-table" ref="tableRef">
                    <el-table :data="tableData" style="width:99.5%" stripe @selection-change="handleSelectionChange"
                        :height="tableHeight">
                        <el-table-column type="selection" width="80" align="center" />
                        <el-table-column fixed prop="username" label="用户名" width="120" align="center" show-overflow-tooltip/>
                        <el-table-column prop="nickname" label="昵称" width="120" align="center" show-overflow-tooltip/>
                        <el-table-column prop="avatar" label="头像" width="100" align="center">
                            <template #default="{ row }">
                                <el-avatar :src="row.avatar" v-if="row.avatar" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="userLevelName" label="会员等级" width="100" align="center" />
                        <el-table-column prop="phone" label="手机" width="120" align="center" />
                        <el-table-column prop="email" label="邮箱" width="180" align="center" show-overflow-tooltip />
                        <el-table-column prop="status" label="状态" width="100" align="center">
                            <template #default="{ row }">
                                <el-switch v-model="row.status" :active-value="1" :inactive-value="0"
                                    style="--el-switch-on-color: var(--primary-theme-color); --el-switch-off-color: #ccc"
                                    @change="changeStatusHandle($event, row)" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="createTime" label="创建时间" width="170" align="center" />
                        <el-table-column prop="updateTime" label="更新时间" width="170" align="center" />
                        <el-table-column fixed="right" label="操作" align="center" width="200">
                            <template #default="{ row }">
                                <el-button type="warning" size="small" @click="openEditUserDrawer(row)"
                                    icon="el-icon-edit">编辑</el-button>
                                <el-button type="danger" size="small" @click="del(row.id)"
                                    icon="el-icon-delete">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="pagination">
                    <el-pagination size="small" background layout="prev, pager, next" :total="total"
                        :page-size="pageSize" @current-change="getDataByPage" />
                </div>
            </div>
        </el-card>
        <drawer ref="drawerRef" :title="isAddMode ? '新增用户' : '修改用户'" direction="rtl" size="35%" @submit="submitHandle">
            <template #rtl>
                <el-form :model="initForm" :rules="formRules" :label-width="100">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="initForm.username"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="initForm.password" type="password"></el-input>
                    </el-form-item>
                    <el-form-item label="昵称" prop="nickname">
                        <el-input v-model="initForm.nickname"></el-input>
                    </el-form-item>
                    <el-form-item label="头像" prop="avatar">
                        <select-image :avatar-url="initForm.avatar" :multiple="false" @select-image="handleImageSelect"  ref="uploadImage"/>
                    </el-form-item>
                    <el-form-item label="会员等级" prop="userLevelId">
                        <el-select-v2 v-model="initForm.userLevelId" :options="levelOptions" filterable
                        v-selectLazyload="getLevelData" placeholder="请选择会员等级" value-key="value"  style="width: 100%" />
 
                    </el-form-item>
                    <el-form-item label="手机" prop="phone">
                        <el-input v-model="initForm.phone"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="initForm.email"></el-input>
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                        <el-switch v-model="initForm.status" :active-value="1" :inactive-value="0"
                            style="--el-switch-on-color: var(--primary-theme-color); --el-switch-off-color: #ccc" />
                    </el-form-item>
                </el-form>
            </template>
        </drawer>
    </div>
</template>

<style lang="scss" scoped>
.userPage {
    height: 100%;

    .card-body {
        height: 100%;
        display: flex;
        flex-direction: column;

        .user-table {
            flex: 1;
            overflow-y: scroll;

            &::-webkit-scrollbar {
                width: 0;
            }
        }

        .pagination {
            height: 50px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }
}

:deep(.el-pagination.is-background .el-pager li.is-active) {
    background-color: var(--primary-theme-color) !important;
    color: #FFFFFF;
}
</style>
